package ro.gateway.aida.struts.action.listers;

import java.util.Iterator;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;

import ro.gateway.aida.db.PersistenceManager;
import ro.gateway.aida.db.PersistenceToken;
import ro.gateway.aida.obj.Country;
import ro.gateway.aida.obj.Person;
import ro.gateway.aida.obj.db.CountryDB;
import ro.gateway.aida.obj.db.PersonDB;
import ro.gateway.aida.struts.MultiTilesAction;
import ro.gateway.aida.struts.form.CountryFilterForm;
import ro.gateway.aida.usr.Arbiter;
import ro.gateway.aida.usr.Perms;
import ro.gateway.aida.usr.UserUtils;
import ro.gateway.aida.utils.PageToken;
import ro.gateway.aida.utils.SortedList;
import ro.gateway.aida.utils.Utils;
import ro.xblue.translator.TranslatorUtils;


/*
 * Created on 08.01.2004
 * Local Projects Database
 * Mihai Postelnicu (mihai@ro-gateway.org)
 * (c) 2003 by eRomania Gateway
 */

/**
 * @author Mihai Postelnicu<p>
 *
 *  e-mail (mihai@ro-gateway.org)<br>
 * (c) 2003 by eRomania Gateway<p>
 */
public class ListPersonsAction extends MultiTilesAction {
    private PersonDB pdb;
    private Arbiter ar;
    private CountryDB cdb;

    public ActionForward modeSelect(ActionMapping mapping, ActionForm form,
        HttpServletRequest request, HttpServletResponse response)
        throws Exception {
        String mode = request.getParameter("mode");

        if (mode == null)
            mode = (String) request.getAttribute("mode");
		
		Utils.setBreadCrumbs(request,"bc.persexp");

        if ("refresh".equals(mode))
            return modeRefresh(mapping, form, request, response);
		if ((mode != null) && mode.matches("[a-z]*Sort"))
		   return modeSort(mapping, form, request, response);

		if (request.getParameter("filter") != null)
					  return modeFilter(mapping, form, request, response);
      		
		if (request.getParameter("csv_list")!=null)
						return modeExport(mapping, form, request, response);

        return modeView(mapping, form, request, response);
    }
    
	public ActionForward modeFilter(ActionMapping mapping, ActionForm form,
		   HttpServletRequest request, HttpServletResponse response)
		   throws Exception {
		   CountryFilterForm cff = (CountryFilterForm) form;
		   HttpSession session = request.getSession();
		   String lang = TranslatorUtils.getCurrentLanguage(request, sc)
										.getLanguage();

		   SortedList sl = (SortedList) session.getAttribute(LIST);
        
		   //the filter
		   sl=pdb.getList();
		   sl.setComparator(new Person.NameComparator());
		   if (!cff.getIso3().equals("ALL")) {
			   Iterator i=sl.iterator();
						   while (i.hasNext()) {
				   Person o = (Person) i.next();
				   if ((o.getCountryISO3().equals(cff.getIso3())))
					   o.setSelected(true);
			   }
			   SortedList sl2=new SortedList();
			   i=sl.iterator();
			   while (i.hasNext()) {
				   Person element = (Person) i.next();
				   if (element.isSelected()) sl2.add(element);
			   }
			   sl=sl2;    
		   }
		   session.setAttribute(LIST,sl);
		   PageToken.tokenizeList( request,  sc, sl, "perss");
	
		   return mapping.getInputForward();
	   }

	public ActionForward modeExport(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response)
			throws Exception {
				return mapping.findForward("csvexport");
			}

    public ActionForward modeSort(ActionMapping mapping, ActionForm form,
        HttpServletRequest request, HttpServletResponse response)
        throws Exception {
        HttpSession session = request.getSession();
        SortedList sl = (SortedList) session.getAttribute(LIST);
        String lang = TranslatorUtils.getCurrentLanguage(request, sc)
                                     .getLanguage();
        String mode = request.getParameter("mode");

        if ("nameSort".equals(mode))
            sl.setComparator(new Person.NameComparator());

        if ("dateSort".equals(mode))
            sl.setComparator(new Person.DateComparator());
        
        PageToken.tokenizeList( request,  sc, sl, "perss");
        
        return mapping.getInputForward();
    }

    public ActionForward modeRefresh(ActionMapping mapping, ActionForm form,
        HttpServletRequest request, HttpServletResponse response)
        throws Exception {
        HttpSession session = request.getSession();
        String lang = TranslatorUtils.getCurrentLanguage(request, sc)
                                     .getLanguage();

        session.setAttribute(LIST, pdb.getList());

        SortedList sl = (SortedList) session.getAttribute(LIST);

        PageToken.tokenizeList( request,  sc, sl, "perss");
        
        return mapping.getInputForward();
    }

    public ActionForward modeView(ActionMapping mapping, ActionForm form,
        HttpServletRequest request, HttpServletResponse response)
        throws Exception {
        HttpSession session = request.getSession();

        SortedList orgs = (SortedList) session.getAttribute(LIST);
        PageToken.tokenizeList( request,  sc, orgs, "perss");
        
        return mapping.getInputForward();
    }

    public ActionForward modePrepare(ActionMapping mapping, ActionForm form,
        HttpServletRequest request, HttpServletResponse response)
        throws Exception {
        String lang = TranslatorUtils.getCurrentLanguage(request, sc)
                                     .getLanguage();
        PersistenceToken token = PersistenceManager.tokenLookup(sc);
		HttpSession session = request.getSession();
        pdb = PersonDB.getManager(token);
        ar = Arbiter.getManager(token);
        cdb = CountryDB.getManager(token);
        

		if (session.getAttribute(Country.LIST) == null)
			session.setAttribute(Country.LIST, cdb.getCountries());


        if (UserUtils.getLogged(request, response) == null)
            return mapping.findForward("plslogin");

        if (!ar.canDo(request, Perms.ADMIN_TOOLS))
            return mapping.findForward("norights");

        SortedList sl = (SortedList) session.getAttribute(LIST);

        if (sl == null)
            request.setAttribute("mode", "refresh");

        return modeSelect(mapping, form, request, response);
    }
	public static final String LIST = "adminPers_LIST";
    
}
